package baseUserService

import (
	"github.com/spf13/cast"
	"learn/app/models/baseUserModel"
	"learn/app/services/cs"
	"learn/pkg/hepler"
)

type User struct {
	cs.BaseService
}

func (obj *User) Add(input map[string]interface{}) (bool, uint64) {

	pwd, err := hepler.EncryptPassword(cast.ToString(input["Pwd"]))
	if err != nil {
		return false, 0
	}
	input["pwd"] = pwd
	inserId := new(baseUserModel.User).Add(input)
	if inserId == 0 {
		return false, inserId
	}
	return true, inserId
}

func (obj *User) List(input map[string]interface{}) ([]map[string]interface{}, int64) {

	user := new(baseUserModel.User)
	user.SetOrderBy("id desc")

	return user.List(input)
}

func (obj *User) Update(input map[string]interface{}) (bool, uint64) {

	if hepler.Empty(input["pwd"]) == false {
		pwd, err := hepler.EncryptPassword(cast.ToString(input["pwd"]))
		if err != nil {
			return false, 0
		}
		input["pwd"] = pwd
	}
	inserId := new(baseUserModel.User).Update(input)
	if inserId == 0 {
		return false, inserId
	}
	return true, inserId
}

func (obj *User) Del(input map[string]interface{}) bool {

	return new(baseUserModel.User).Del(input)

}

func (obj *User) Login(input map[string]interface{}) (bool, map[string]interface{}) {

	pwd, err := hepler.EncryptPassword(cast.ToString(input["Pwd"]))
	if err != nil {
		return false, nil
	}
	input["pwd"] = pwd
	if user := new(baseUserModel.User).Find(input); user != nil {
		return true, user
	} else {
		return false, nil
	}

}
